#!groovy

library 'pi8-pipeline-library'

def map = [:]

call(map)

def call(Map map) {

    pipeline {
        agent {label "${APP_NODE}"}

        options{
            skipDefaultCheckout()
            timeout(time:5,unit:'MINUTES')
        }

        environment {
            package_name = "${PKG_NAME}"
            package_dir = "${PKG_DIR}"
            deploy_tag = "${ENV_TAG}"
        }

        stages {
            stage("清理workspace"){
                steps {
                    sh "mkdir -p work_home/log_bak"
                    catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                        sh "mv app.log work_home/log_bak/app.log_bak_${env.BUILD_NUMBER}"
                        sh "find * | grep -v work_home | xargs rm -rf"
                    }
                }
            }

            stage("git pull") {
                steps {
                    git branch: "${BRANCH}", url: "git@gitee.com:private-in-8-lab/team-2.git"
                }
            }

            stage("build service") {
                steps {
                    sh "echo `pwd`"
                    sh "ls"
                    withMaven(maven: 'maven3.6.3') {
                        sh "mvn -version"
                        sh "java -version"
                        sh "cd ${package_dir}"
                        sh "mvn clean package -e -U -P ${deploy_tag} -Dmaven.test.skip=true"
                    }
                }
            }

            stage("kill app") {
                steps {
                    echo "kill slave1"
                    catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                        sh "ps -aef |grep java |grep '${package_name}'|grep -v grep |sed 's/ [ ]*/:/g' |cut -d: -f2 |xargs kill -9"
                    }
                }
            }

            stage("start app") {
                steps {
                    sh "mv ${package_dir}/target/${package_name} work_home/${package_name}"
                    dir(path: "work_home") {
                        withEnv(['JENKINS_NODE_COOKIE=dontkill']) {
                            sh "nohup java -Duser.timezone=GMT+08 -server -Xms1g -Xmx1g -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -jar ${package_name} > ../app.log 2>&1 &"
                        }
                    }
                }
            }
        }


        post {
            always{
                echo "always......"
            }
            success{
                echo "success......"
            }
            failure{
                echo "failure......"
            }
            unstable{
                echo "unstable......"
            }

        }
    }
}